/* ===================================================
 *	IBBD CLASS
 * ===================================================
 *    IBBDchart
 *    IBBDmap
 *    IBBDtable
 *	  IBBDpager
 *    IBBDDatepicker
 *    IBBDtips
 *    IBBDtips2
 *    IBBDselectbox
 * ===================================================
 *	by IBBD dev-team
 * =================================================== */

/* IBBDtable PUBLIC CLASS DEFINITION
     * ==================================
		作用:IBBD 表格类
		参数:
			container = $('div') //表格容器，jquery对象
			options = {
				rankOptions:{}   //排序选项,参数参考插件tablesorter,可选
			}
       ================================== */
var IBBDtable = function(container, options) {
	this.init(container, options);
}

/* 初始化
 * ================================== */
IBBDtable.prototype.init = function(container, options) {
	this.container = container;
	this.options = options || {};
	this.dataTable = new Array(); //表格数据(可扩展为数据模型类)
	if (this.options.rankOptions) {
		// 初始化可排序表格,使用插件tablesorter
		this.initRank = true;
		this.container.addClass('tablesorter');
		// @author 	Cooper
		this.options.rankOptions.textExtraction = function(node) {
			var node_obj = $(node).html();
			node_obj = node_obj.replace(new RegExp(',', 'gm'), '')
			if (node_obj.indexOf("￥") > -1) {
				node_obj = node_obj.replace(new RegExp('￥', 'gm'), '');
			}
			return node_obj;
		}
	}
}

/* 设置表格列
 * header 列明数组
 * ================================== */
IBBDtable.prototype.setHeader = function(header) {
	// clear current thead
	this.container.find("thead").html("");
	var thead = $("<thead/>");
	$.each(header, function(i, val) {
		$("<th/>", {
			html: val
		}).appendTo(thead);
	});
	this.container.find("thead").html(thead.html());
}

/* 设置表格数据
 * ================================== */
IBBDtable.prototype.setTableData = function(tableData) {
	this.dataTable = tableData;
}

/* 重设表格
 * ================================== */
IBBDtable.prototype.reset = function() {
	this.container.find('tbody').empty();
}

/* 画表格
     * ==================================
		参数:
			customItem = {  //自定义单元格模板,可选
				img: function(data){
					return '<img src="'+data['img']+'" />';
				}
			}
			详细用法见前端文档
       ================================== */
IBBDtable.prototype.drawTable = function(customItem) {
	if ($.isEmptyObject(this.dataTable)) {
		return false;
	}
	var itemType = { //6种单元格基本类型
		icon: function(tdData, td) {
			return '<i class="icon-search"></i>';
		},
		img: function(tdData) {
			if (tdData['href']) {
				return '<a href="' + tdData['href'] + '" target="_blank"><img src="' + tdData['img'] + '"></a>';
			} else {
				return '<img src="' + tdData['img'] + '">';
			};
		},
		link: function(tdData) {
			return '<a href="' + tdData['link'] + '" target="_blank">' + (tdData['name'] ? tdData['name'] : '-') + '</a>';
		},
		progress: function(tdData) {
			return '<div class="progress progress-striped"><div class="bar" style="width: ' + tdData['progress'] + '%;"></div></div>';
		},
		checkbox: function() {
			return '<input class="manageCheckBox" type="checkbox">';
		},
		price: function(tdData, td) {
			var num = tdData['price'];
			if (num < 1000) {
				num = num.toFixed(2);
			} else {
				num = parseInt(num);
			}
			return fToScientificNotation(num);
			// return '￥' + fToScientificNotation(tdData['price']);
		},
		num: function(tdData, td) {
			return fToScientificNotation(tdData['num']);
		},
		percent: function(tdData, td) {
			return (tdData['percent'] * 100).toFixed(2) + '%';
		}
	}
	var itemStyle = {
		icon: 'align-center',
		price: 'align-right',
		num: 'align-right',
		percent: 'align-right'
	};
	if (customItem) {
		this.options.customItem = customItem;
		$.extend(itemType, customItem);
	};
	this.container.children('tbody').empty();
	for (var i = 0, iLen = this.dataTable.length; i < iLen; i++ ) {
		var trHtml = $('<tr/>');
		var trItem = this.dataTable[i];
		for (var j = 0, jLen = trItem.length; j < jLen; j++) {
			var tdHTML = $('<td/>'),
				tdText = '-';
			if ($.isPlainObject(trItem[j])) {
				for(var key in trItem[j]) {
					if(itemType.hasOwnProperty(key)){
						tdHTML.addClass(itemStyle[key] || '');
						var tdItem = trItem[j][key];
						if ( tdItem !== undefined && tdItem !== null && tdItem !== '' ) {
							tdText = itemType[key](trItem[j], tdHTML);
							break;
						}
					}
				}
			} else {
				tdText = trItem[j];
			}
			tdHTML.append(tdText).appendTo(trHtml);
			this.container.children('tbody').append(trHtml);
		}
	}
	if (this.initRank) {
		this.container.tablesorter(this.options.rankOptions);
		this.initRank = false;
	} else {
		if (this.options.rankOptions) {
			this.container.trigger('update');
			var sortList = this.options.rankOptions.sortList || [];
			var container = this.container;
			setTimeout(function(){
				container.trigger('sorton', [sortList]);
			}, 1);
		};
	}
}

/* 更新表格
     * ==================================
     	参数
     		ajaxUrl = '' //ajax请求地址
     		askData = {} //请求参数
       ================================== */
IBBDtable.prototype.updateTable = function(ajaxUrl, askData, callback) {
	var self = this;
	self.reset();
	$.get(ajaxUrl, askData, function(result) {
		var tableData = result.data || result.rows; //兼容rows数据
		self.setTableData(tableData);
		self.drawTable(self.options.customItem);
		if (callback) {
			callback();
		}
	}, 'json');
}

/* ========IBBDtable Class End==============
 * Update: 2012/8/17 TODO!
 * by weishai
 * ========================================================== */



/* IBBDpager PUBLIC CLASS DEFINITION
     * ==================================
		作用:IBBD分页类
		参数
			container = $('div') //分页容器,jquery对象
			options = {
				pageCount:, //总页数,必填
				pageSize:9, //页面(按钮)数量,默认9
				curPage:1,  //初始化时当前页,默认1
			}
       ================================== */
var IBBDpager = function(container, options) {
	this.init(container, options);
}

/* 初始化
 * ================================== */
IBBDpager.prototype.init = function(container, options) {
	this.container = container;
	var defaultOptions = {
		pageSize: 9,
		curPage: 1,
		allBtn: false
	}
	this.options = $.extend({}, defaultOptions, options);
	this.curPage = this.options.curPage;
	this.pageSize = this.options.pageSize;
	this.pageCount = this.options.pageCount || 0;
	if (this.pageCount >= 10) { //总页数大于10页，自动显示首尾页按钮
		this.options.allBtn = true;
	}
	this.update();
}

/* 构造分页HTML
 * ================================== */
IBBDpager.prototype.render = function() {
	if (this.pageCount < 1) {
		this.pageCount = 1;
	};
	var self = this,
		startPoint = 1,
		endPoint = this.pageSize,
		offset = Math.floor((endPoint - 1) / 2),
		$pagerHTML = $('<ul><li class="prev"><a href="#">上一页</a></li></ul>')
		if (this.curPage > offset) {
			startPoint = this.curPage - offset;
			endPoint = this.curPage + (endPoint - offset - 1);
		}
	if (endPoint > this.pageCount) {
		startPoint = this.pageCount - offset * 2;
		endPoint = this.pageCount;
	}
	if (startPoint < 1) {
		startPoint = 1;
	}
	for (var pn = startPoint; pn <= endPoint; pn++) {
		var $curBtn = $('<li class="pn"><a href="#">' + (pn) + '</a></li>');
		pn == this.curPage ? $curBtn.addClass('active').click(false) : (function(thisBtn, thisPn) {
			thisBtn.click(function() {
				self.curPage = thisPn;
				self.options.clickPn(thisPn);
				self.update();
				return false;
			});
		})($curBtn, pn);
		$curBtn.appendTo($pagerHTML);
	}
	$pagerHTML.append('<li class="next"><a href="#">下一页</a></li>');

	if (this.options.allBtn) {
		$pagerHTML.prepend('<li class="first-page"><a href="#">首页</a></li>').append('<li class="last-page"><a href="#">尾页</a></li>')
	}

	if (this.curPage <= 1) {
		$pagerHTML.children('.prev,.first-page').addClass('disabled').click(false);
	} else {
		$pagerHTML.children('.prev').click(function() {
			$pagerHTML.children('.active').prev().click();
			return false;
		})
			.parent().children('.first-page').click(function() {
				self.curPage = 1;
				self.options.clickPn(1);
				self.update();
				return false;
			})
	}

	if (this.curPage >= this.pageCount) {
		$pagerHTML.children('.next,.last-page').addClass('disabled').click(false);
	} else {
		$pagerHTML.children('.next').click(function() {
			$pagerHTML.children('.active').next().click();
			return false;
		})
			.parent().children('.last-page').click(function() {
				self.curPage = self.pageCount;
				self.options.clickPn(self.pageCount);
				self.update();
				return false;
			})
	}
	this.container.empty();
	this.container.append($pagerHTML);
}

/* 更新分页
 * ================================== */
IBBDpager.prototype.update = function() {
	this.render();
}

/* ========IBBDpager Class End==============
 * Update: 2012/8/17 TODO!
 * by weishai
 * ========================================================== */

/* 工具函数
 * ================================ */

// 格式化日期

function formatDate(original_date) {
	var year = original_date.getFullYear();
	var month = original_date.getMonth() + 1;
	if (month < 10) {
		month = '0' + month;
	}
	var date = original_date.getDate();
	if (date < 10) {
		date = '0' + date;
	}
	return year + '-' + month + '-' + date;
}


/* 将数字转换为三位科学计数法，用逗号隔开（只支持整数和小数点后最多三位）
 * by knowingluing 2012.08.22
 */

function fToScientificNotation(sNum) {
	if (sNum === null || sNum === undefined) {
		return '-';
	}
	try {
		sNum = sNum.toString();
	} catch (e) {
		return '-';
	}
	var sResult = sNum.replace(/(\d)(\d{3})$/, "$1,$2");
	var sResult = sResult.replace(/(\d)(\d{3})\./, "$1,$2.");
	for (var jj = 0; jj < Math.round(sNum.length / 3); jj++) {
		sResult = sResult.replace(/(\d)(\d{3}),/, "$1,$2,");
	}
	return sResult;
}

/* js小数乘法 */

function accMul(arg1, arg2) {
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length
	} catch (e) {}
	try {
		m += s2.split(".")[1].length
	} catch (e) {}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

/*
 * 编写蔡镇波
 * 日期选择器的封装
 *
 */
var IBBDDatepicker = function(fromDate, toDate) {
	this.init(fromDate, toDate);
}

IBBDDatepicker.prototype.init = function(from, to, maxDate) {
	var today = new Date();
	$('#' + to).val(formatDate(new Date(today - 1000 * 60 * 60 * 24)));
	$('#' + from).val(formatDate(new Date(today - 1000 * 60 * 60 * 24 * 7))); //默认设置为一周
	$('#' + from + ', #' + to).datepicker({
		changeMonth: true,
		changeYear: true,
		constrainInput: true,
		dateFormat: "yy-mm-dd",
		duration: 'fast',
		hideIfNoPrevNext: true,
		monthNamesShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
		dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
		selectOtherMonths: true,
		showAnim: 'fadeIn',
		showOtherMonths: true,
		showWeek: false,
		yearSuffix: '',
		'maxDate': maxDate || new Date()
	}).change(function() {
		var selectedDate = this.value;
		var option = (this.id == from) ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings); // 获取并解析当前input框所填的日期
		$('#' + from + ', #' + to).not(this).datepicker("option", option, date);
	});
}




/* ie7、8不支持Array.indexOf，为其拓展定义一个 
 * ==================================*/
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elem) {
		var i = 0,
			len = this.length;
		for (; i < len; i++) {
			if (this[i] === elem) {
				return i;
			}
		}
		return -1;
	}
}

